# Chat API endpoints
from typing import Optional
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, update, func
from datetime import datetime

from ...database import get_db
from ...core.auth import get_current_user
from ...core.config import NovelProject
from ...models.user import User
from ...models.chat import ChatSession
from ...models.message import ChatMessage
from ...schemas.chat import (
    SendMessageRequest, 
    ChatResponse, 
    ChatSessionResponse, 
    ChatMessageResponse,
    SenderType
)
from ...services.ai_service import AIConversationService
from ...core.config import settings

router = APIRouter()
ai_service = AIConversationService()


@router.post("/send", response_model=ChatResponse)
async def send_message(
    request: SendMessageRequest,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    """发送消息并获取AI回复"""
    try:
        # 获取或创建会话
        if request.session_id:
            # 获取现有会话
            stmt = select(ChatSession).where(
                ChatSession.id == request.session_id,
                ChatSession.user_id == current_user.id,
                ChatSession.is_active == True
            )
            result = await db.execute(stmt)
            session = result.scalar_one_or_none()
            
            if not session:
                raise HTTPException(
                    status_code=status.HTTP_404_NOT_FOUND,
                    detail="会话不存在或无权访问"
                )
        else:
            # 创建新会话
            session = ChatSession(
                user_id=current_user.id,
                avatar_id=1,  # 暂时使用默认数字人ID
                character_id=request.character_id,
                title=f"与{request.character_name}的对话",
                session_type="roleplay",
                roleplay_context=f"扮演《{request.novel_title}》中的{request.character_name}",
                is_active=True
            )
            db.add(session)
            await db.flush()  # 获取session.id
        
        # 保存用户消息
        user_message = ChatMessage(
            session_id=session.id,
            sender_type=SenderType.USER,
            content=request.message,
            content_type="text"
        )
        db.add(user_message)
        
        # 调用AI服务获取回复
        ai_response = await ai_service.chat_with_character(
            character_name=request.character_name,
            novel_project=NovelProject(request.novel_project),
            user_message=request.message,
            conversation_history=None  # TODO: 
        )
        
        # 保存AI回复消息
        character_message = ChatMessage(
            session_id=session.id,
            sender_type=SenderType.AVATAR,
            content=ai_response.get("content", "抱歉，我现在无法回应。"),
            content_type="text",
            emotion="neutral"  # TODO: 从AI响应中提取情感
        )
        db.add(character_message)
        
        # 更新会话信息
        session.message_count = func.coalesce(session.message_count, 0) + 2
        session.last_message_at = datetime.utcnow()
        session.updated_at = datetime.utcnow()
        
        await db.commit()
        await db.refresh(session)
        await db.refresh(character_message)
        
        # 构建响应
        return ChatResponse(
            success=True,
            session=ChatSessionResponse.model_validate(session),
            character_message=ChatMessageResponse.model_validate(character_message)
        )
        
    except Exception as e:
        await db.rollback()
        return ChatResponse(
            success=False,
            session=None,
            character_message=None,
            error=str(e)
        )


@router.get("/sessions", response_model=list[ChatSessionResponse])
async def get_user_sessions(
    limit: Optional[int] = 20,
    offset: Optional[int] = 0,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    """获取用户的会话列表"""
    stmt = (
        select(ChatSession)
        .where(
            ChatSession.user_id == current_user.id,
            ChatSession.is_active == True
        )
        .order_by(ChatSession.updated_at.desc())
        .limit(limit)
        .offset(offset)
    )
    
    result = await db.execute(stmt)
    sessions = result.scalars().all()
    
    return [ChatSessionResponse.model_validate(session) for session in sessions]


@router.get("/sessions/{session_id}/messages", response_model=list[ChatMessageResponse])
async def get_session_messages(
    session_id: int,
    limit: Optional[int] = 50,
    offset: Optional[int] = 0,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    """获取会话的消息历史"""
    # 验证会话权限
    session_stmt = select(ChatSession).where(
        ChatSession.id == session_id,
        ChatSession.user_id == current_user.id
    )
    session_result = await db.execute(session_stmt)
    session = session_result.scalar_one_or_none()
    
    if not session:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="会话不存在或无权访问"
        )
    
    # 获取消息
    messages_stmt = (
        select(ChatMessage)
        .where(
            ChatMessage.session_id == session_id,
            ChatMessage.is_deleted == False
        )
        .order_by(ChatMessage.created_at.asc())
        .limit(limit)
        .offset(offset)
    )
    
    messages_result = await db.execute(messages_stmt)
    messages = messages_result.scalars().all()
    
    return [ChatMessageResponse.model_validate(message) for message in messages]


@router.delete("/sessions/{session_id}")
async def delete_session(
    session_id: int,
    current_user: User = Depends(get_current_user),
    db: AsyncSession = Depends(get_db)
):
    """删除会话（软删除）"""
    stmt = (
        update(ChatSession)
        .where(
            ChatSession.id == session_id,
            ChatSession.user_id == current_user.id
        )
        .values(is_active=False, updated_at=datetime.utcnow())
    )
    
    result = await db.execute(stmt)
    
    if result.rowcount == 0:
        raise HTTPException(
            status_code=status.HTTP_404_NOT_FOUND,
            detail="会话不存在或无权访问"
        )
    
    await db.commit()
    return {"message": "会话已删除"} 